﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;

using CNCSoft.EWinform;
using CNCSoft.EWinform.ControlUtils;
using CNCSoft.EWinform.ERPApps;
using CNCSoft.EWinform.AGrid;
using CNCSoft.EData;
using Common;


namespace CNCSoft.ErpApps.TMS.Study
{
    public partial class frmBrowse : Form
    {

        frmBrowseData BrowseData;
        DataGridAutoResizeSupporter dgridARS = new DataGridAutoResizeSupporter();
        DataGridStyleFactory dgridSF = new DataGridStyleFactory();

        //Xac dinh danh muc
        string SQL_SELECT = "";
        string SQL_UPDATE = "";
        //Xac dinh Mã chính của danh mục cần thêm (không phải mã FK tham khảo đên các DM khác)
        string strMaKey;


        public frmBrowse(string strSQL_SELECT, string strSQL_UPDATE, string strMaChinhCuaDanhMuc, string strTieuDeForm)
        {
            InitializeComponent();
            this.Text = strTieuDeForm;

            SQL_SELECT = strSQL_SELECT;
            SQL_UPDATE = strSQL_UPDATE;
            if (strSQL_UPDATE == "") strSQL_UPDATE = strSQL_SELECT;  //Truong hop 2 cau giong nhau thi ko can truyen cau UPDATE
            strMaKey = strMaChinhCuaDanhMuc;
        }

        private void frmBrowse_Load(object sender, EventArgs e)
        {
            BrowseData = new frmBrowseData();  //Init and fill data to table "DANHMUC"
            BrowseData.fill(SQL_SELECT);
            
            BrowseData.getTable(frmBrowseData.TL.DanhMuc).ColumnChanged += new DataColumnChangeEventHandler(frmBrowse_ColumnChanged);

            dg.SetDataBinding(BrowseData.getDataSet(), "DANHMUC");   //Binding DataGrid with table DANHMUC

            ApplyTableStyle();

            cmdRefresh_Click(sender,e);

        }


        private void frmBrowse_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            //if (e.Column.ColumnName.ToUpper() == strMaKey.ToUpper() ) return;   //Khong co load de tim du lieu cho truong co ten la <MAKEY>

            string Ma = "";
            string DanhMuc = "";
            string Ten = "";

            if (e.Column.ColumnName.ToUpper().Substring(0,2) == "MA")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = e.Column.ColumnName.ToUpper().Replace("MA", "DM_");
                Ten = e.Column.ColumnName.ToUpper().Replace("MA", "TEN");
                //Khong co trong danh muc la hien list data
            }

            //Cac truong hop can liet ke (khong thuoc kieu MAxx, DM_xxx)
            if (e.Column.ColumnName.ToUpper() == "MATOTRUONG" || e.Column.ColumnName.ToUpper() == "MAKHOITRUONG" || e.Column.ColumnName.ToUpper() == "MAKHOIPHO")  //Giao vien truong bo mon
            {
                Ma = "MaGiaoVien";
                DanhMuc = "DM_GIAOVIEN";
                Ten = "TenGiaoVien";
            }
            if (e.Column.ColumnName.ToUpper() == "MAHOCTAP")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = "View_DanhSachHocVien";
                Ten = "HoTenHV";
            }
            if (e.Column.ColumnName.ToUpper() == "ENQUIRYNUMBER")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = " (Select distinct EnquiryNumber, Holot + ' ' + Ten as HoTenHV from Enquiry) as Data ";
                Ten = "HoTenHV";
            }
            if (e.Column.ColumnName.ToUpper() == "INVOICENUMBER")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = " (Select distinct InvoiceNumber, HoTenHV from View_Invoice) as Data ";
                Ten = "HoTenHV";
            }

            if (e.Column.ColumnName.ToUpper() == "ENROLLNUMBER")
            {
                Ma = e.Column.ColumnName.ToUpper();
                DanhMuc = " (Select distinct  InvoiceNumber as EnrollNumber, HoTenHV from View_Invoice) as Data ";
                Ten = "HoTenHV";
            }

            if (Ma == "") return;

            //Read only cot Ten
            if (Ten != "")
                try
                {
                    dg.TableStyles[0].GridColumnStyles[Ten].ReadOnly = true;
                }  catch { }

            try  //Neu ko co se xuong catch
            {
                string str = CNCSoft.EData.SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                            "SELECT " + Ma + " FROM " + DanhMuc + " WHERE " + Ma + " = '" + e.Row[e.Column.ColumnName] + "'").ToString();
            }
            catch (Exception ex)
            {
                //Can xu ly them truong hop khong co DanhMuc (do ngo nhan ten MA...)
                if (ex.Message.IndexOf("'" + DanhMuc + "'") < 0)  //Bao loi lien quan den Danh Muc (Invalid Object name <DM>). Khong co DanhMuc thi thoi, ko load data list lam gi
                {
                    e.Row[e.Column.ColumnName] = LoadListData("SELECT * FROM " + DanhMuc);
                    try
                    {
                        e.Row[Ten] = CNCSoft.EData.SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                                "SELECT " + Ten + " FROM " + DanhMuc + " WHERE " + Ma + " = '" + e.Row[e.Column.ColumnName] + "'").ToString();
                    } catch { }

                    return;
                }
            }
        }

        
        private string LoadListData(string strSELECT)
        {
            try
            {
                FormView fv = null;
                fv = new FormView(strSELECT, GlobalVariable.WSInfo.ConnectionString, GlobalVariable.WSInfo.WorkingDate);
                //fv.DateFilterColumns = new string[,] { { "NgayDeNghi", "Ngày yêu cầu" } };
                //fv.CollumnFocusInFilterGrid = 3;

                fv.ShowDialog(this);
                if (fv.DialogResult == DialogResult.OK)
                {
                    return fv.SelectedIDs.Replace("'", "").Replace("(", "").Replace(")", "");
                }
                else
                    return "";
            }
            catch
            {
                return "";
            }
        }

       
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            BrowseData.update(SQL_UPDATE);            
            
            //Load lai
            BrowseData.getTable(frmBrowseData.TL.DanhMuc).Clear();
            BrowseData.fill(SQL_SELECT);
            dg.Refresh();

            //Hien so records
            DataView ViewRecord = BrowseData.getTable(frmBrowseData.TL.DanhMuc).DefaultView;
            lblSoRecord.Text = "Có " + ViewRecord.Count.ToString("G") + " records";
        }

        private void cmdRefresh_Click(object sender, EventArgs e)
        {
            if (BrowseData.getTable(frmBrowseData.TL.DanhMuc).GetChanges() != null)
            {
                DialogResult dr = MessageBox.Show(this, "Dữ liệu có thay đổi!\nBạn có muốn lưu lại trước khi refresh số liệu không ?",
                    "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    btnUpdate_Click(btnUpdate , e);
                }
                
            }
            BrowseData.getTable(frmBrowseData.TL.DanhMuc).Clear();
            BrowseData.fill(SQL_SELECT);
            dg.Refresh();

            //Hien so records
            DataView ViewRecord = BrowseData.getTable(frmBrowseData.TL.DanhMuc).DefaultView;
            lblSoRecord.Text = "Có " + ViewRecord.Count.ToString("G") + " records";
        }


        private void ApplyTableStyle()
        {
            DataTable tblDL = null;
            tblDL = BrowseData.getTable(frmBrowseData.TL.DanhMuc);


            DataGridTableStyle ts = new DataGridTableStyle();
			ts.MappingName = tblDL.TableName;

			DataColumn dc;

			for (int indexCol = 0; indexCol < tblDL.Columns.Count; indexCol++) 
            {
                string dtType = tblDL.Columns[indexCol].DataType.ToString();
				dc = tblDL.Columns[indexCol];
				if (dtType ==  "System.Int16" || dtType ==  "System.Int32" || dtType ==  "System.Int64") {
					AGridTextBoxColumn dgridFTC = new AGridTextBoxColumn();
					dgridFTC.MappingName = dc.ColumnName;
					dgridFTC.HeaderText = dc.ColumnName;
					dgridFTC.NullText = "";
					dgridFTC.Format = "N0";
					ts.GridColumnStyles.Add(dgridFTC);

				} else if (dtType ==  "System.Decimal" || dtType ==  "System.Double") {
					AGridTextBoxColumn dgridFTC = new AGridTextBoxColumn();
					dgridFTC.MappingName = dc.ColumnName;
					dgridFTC.HeaderText = dc.ColumnName;
					dgridFTC.NullText = "";
					dgridFTC.Format = "N";
					ts.GridColumnStyles.Add(dgridFTC);

				} else if (dtType ==  "System.Boolean") {
					AGridClickableBoolColumn BoolCol = new AGridClickableBoolColumn();
					BoolCol.MappingName = dc.ColumnName;
					BoolCol.HeaderText = dc.ColumnName;
					BoolCol.Alignment = HorizontalAlignment.Center;
					BoolCol.NullText = "";
					BoolCol.AllowNull = false;
					ts.GridColumnStyles.Add(BoolCol);

				} 
                /*else if (dtType ==  "System.DateTime") {
					AGridDateTimeColumn dtCol = new AGridDateTimeColumn();
					dtCol.MappingName = dc.ColumnName;
					dtCol.HeaderText = dc.ColumnName;
					dtCol.Alignment = HorizontalAlignment.Center;
					dtCol.NullText = "";
					dtCol.DateTimePicker.Format = DateTimePickerFormat.Short;
					ts.GridColumnStyles.Add(dtCol);
				}*/ else {
					AGridTextBoxColumn dgridFTC = new AGridTextBoxColumn();
					dgridFTC.MappingName = dc.ColumnName;
					dgridFTC.HeaderText = dc.ColumnName;
					dgridFTC.NullText = "";
					ts.GridColumnStyles.Add(dgridFTC);
				}

                if (dc.ColumnName == "ID" ) 
                {
					ts.GridColumnStyles[indexCol].HeaderText = "";
					ts.GridColumnStyles[indexCol].Width = 0;
				}

				
			} // for (int indexCol = 0; indexCol < tblDL.Columns.Count; indexCol++)

			dg.TableStyles.Add(ts);
			DataGridStyleFactory dgridSF = new DataGridStyleFactory();
			dgridSF.applyStyleUseRandom(dg);

			DataGridAutoResizeSupporter gridARS = new DataGridAutoResizeSupporter(dg);
			gridARS.AutoSizeGrid();

            /*
            //AddHandler
            for (int x = 2; x<= dg.Controls.Count - 1 ; x++)
            {
                dg.Controls[x].KeyDown += new KeyEventHandler(c_KeyPress);   
            }
            */

        }

        /*
        frmFind ff = null;

        private void c_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e) 
        {
            if ( e.Control &&  e.KeyCode == Keys.F )
            {
                string colName = GetCurrentColumnName();
                DataView ViewRecord = BrowseData.getTable(frmBrowseData.TL.DanhMuc).DefaultView;
                try
                {
                    if (ff == null)
                        ff = new frmFind();

                    ff.SetFilterCaption = colName;
                    ff.ShowDialog(this);

                    if (ff.DialogResult == DialogResult.OK)
                    {
                        string strExFilter = "[" + colName + "]" + " like " + "'%" + ff.strReturnValue + "%' ";
                        ViewRecord.RowFilter = strExFilter;
                        dg.DataSource = ViewRecord;
                        lblSoRecord.Text = "Có " + ViewRecord.Count.ToString("G") + " records";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    
        */

        private string GetCurrentColumnName()
        {
            try
            {
                int colNo;

                if (BrowseData.getTable(frmBrowseData.TL.DanhMuc) != null)
                {
                    colNo = this.dg.CurrentCell.ColumnNumber;
                    return this.dg.TableStyles[0].GridColumnStyles[colNo].MappingName.ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                return string.Empty;
            }
        }


    }


    
}